package com.polaris.live.widget.bubble

import android.graphics.Rect
import java.nio.ByteBuffer
import java.nio.ByteOrder

/**
 * NinePatchChunk  用来获取点9图里面的边界信息
 * @author Created by 天晴 on 2024/1/29 20:18
 * @since 1.0.0
 **/

class NinePatchChunk {

    val mPaddings = Rect()
    var mDivX: IntArray? = null
    var mDivY: IntArray? = null
    var mColor: IntArray? = null

    companion object {

        const val NO_COLOR = 0x00000001
        const val TRANSPARENT_COLOR = 0x00000000
        private fun readIntArray(data: IntArray, buffer: ByteBuffer) {
            var i = 0
            val n = data.size
            while (i < n) {
                data[i] = buffer.int
                ++i
            }
        }

        private fun checkDivCount(length: Int) {
            if (length == 0 || length and 0x01 != 0) throw RuntimeException("invalid nine-patch: $length")
        }

        fun deserialize(data: ByteArray?): NinePatchChunk? {
            if (data == null) {
                return null
            }

            val byteBuffer = ByteBuffer.wrap(data).order(ByteOrder.nativeOrder())
            if (byteBuffer.get().toInt() == 0) return null
            val chunk = NinePatchChunk()
            chunk.mDivX = IntArray(byteBuffer.get().toInt())
            chunk.mDivY = IntArray(byteBuffer.get().toInt())
            chunk.mColor = IntArray(byteBuffer.get().toInt())
            chunk.mDivX?.let {
                checkDivCount(it.size)
            }
            chunk.mDivY?.let {
                checkDivCount(it.size)
            }
            // skip 8 bytes
            byteBuffer.int
            byteBuffer.int
            chunk.mPaddings.left = byteBuffer.int
            chunk.mPaddings.right = byteBuffer.int
            chunk.mPaddings.top = byteBuffer.int
            chunk.mPaddings.bottom = byteBuffer.int
            // skip 4 bytes
            byteBuffer.int

            chunk.mDivX?.let {
                readIntArray(it, byteBuffer)
            }
            chunk.mDivY?.let {
                readIntArray(it, byteBuffer)
            }
            chunk.mColor?.let {
                readIntArray(it, byteBuffer)
            }
            return chunk
        }
    }
}